//
//  OAuthViewController.swift
//  weibo1
//
//  Created by changhongliang on 2017/7/24.
//  Copyright © 2017年 richinfo. All rights reserved.
//

import UIKit
import SVProgressHUD


class OAuthViewController: UIViewController,UIWebViewDelegate {
    
    override func loadView() {
        view = webview

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "大亮"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.plain, target: self, action: #selector(OAuthViewController.close))
        //加载授权界面
        loadOAuthPage()
    }
    
    func close() {
      self.dismiss(animated: true, completion: nil)
    }
    
    private func loadOAuthPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_REDIRECT_URI)"
        let url = NSURL(string: urlString)!
        let request = NSURLRequest(url: url as URL)
        webview.loadRequest(request as URLRequest)
        
    }
    
    private lazy var webview:UIWebView = {
    let wv = UIWebView()
    wv.delegate = self
    return wv
    }()
    
}

extension OAuthViewController {
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let ulrString = request.url?.absoluteString
        if !(ulrString?.hasPrefix(WB_REDIRECT_URL))!{
            return true
        }
        
        let query = request.url?.query
        let codeString = "code="
        if (query?.hasPrefix(codeString))! {
            let code = query?.substring(from: codeString.endIndex)
            HLLog("获取授权Token")
            HLLog("code:\(String(describing: code))")
            //获取AccessToken
            loadAccessToken(code: code!)
           
        }else{
            HLLog("没有未授权Token")
            close()
        }
        return  false
    }
    
    func loadAccessToken(code:String) {
        
        let urlString = "oauth2/access_token"
        let params = ["client_id": WB_Client_ID,
                      "client_secret": WB_Client_Secret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": WB_REDIRECT_URI
        ]
        
        NetworkTools.requestData(.post, URLString: urlString, parameters: params) { (result, error) in
            let uerAccount = UserAccount(dict: result!)
            //获取用户信息
            self.loadUserInfo(account: uerAccount)
        }
        
    }
    
    //获取用户信息
    private func loadUserInfo(account:UserAccount) {
        let path = "2/users/show.json"
        let paramaters = ["access_token":account.access_token!,
                          "uid":account.uid!
                          ]
        NetworkTools.requestData(.get, URLString: path, parameters: paramaters) { (result, error) in
            account.screen_name = result?["screen_name"] as? String 
            account.avatar_large = result?["avatar_large"] as? String
            //保存模型
            account.saveAccount()
            NotificationCenter.default.post(name:NSNotification.Name(rawValue: HLSwitchMainInterfaceNotification), object: false)
            
        }
        
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.showInfo(withStatus: "正在加载网页.....")
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
   


}
